package com.websocket.configurator;


import com.websocket.util.Contains;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;


/**
 * Created by simon on 5/20/17.
 */
public class HttpSessionConfigurator extends Configurator {
    private static Logger logger = LoggerFactory.getLogger(HttpSessionConfigurator.class);

    @Override
    public void modifyHandshake(ServerEndpointConfig serverEndpointConfig,
                                HandshakeRequest handshakeRequest, HandshakeResponse handshakeResponse) {
        Object httpSessionObject = handshakeRequest.getHttpSession();
        if (httpSessionObject == null) {
            return;
        }
        HttpSession httpSession = (HttpSession) httpSessionObject;
        if (httpSession == null) {
            return;
        }
        serverEndpointConfig.getUserProperties().put(HttpSession.class.getName(), httpSession);

        String sec_websocket_key = handshakeRequest.getHeaders().get(HandshakeRequest.SEC_WEBSOCKET_KEY).get(0);
        // for log4j
        ThreadContext.put(Contains.X_SOCKET_KEY, sec_websocket_key);
    }
}

